<template>
  <div class="app-container">
    <!-- 查询模块 -->
    <div class="formDiv">
      <el-form ref="form" :inline="true" :model="form" label-width="130px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="补贴单号">
              <el-input v-model="form.applySn"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="姓名">
              <el-input v-model="form.realname"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="手机号">
              <el-input v-model="form.username"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="省市">
              <el-cascader placeholder="请选择省市" @change="handleChange" clearable :options="options" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="医院名称">
              <el-select placeholder="请选择" v-model="form.hospitalId">
                <el-option
                  v-for="item in hospitalOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="报单时间">
              <el-date-picker
                value-format="yyyy-MM-dd HH:mm:ss"
                v-model="createdAt"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="退款时间">
              <el-date-picker
                value-format="yyyy-MM-dd HH:mm:ss"
                v-model="refundTime"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="退款状态">
              <el-select placeholder="请选择" v-model="form.refundStatus">
                <el-option label="全部" :value="null"></el-option>
                <el-option label="退款成功" :value="0"></el-option>
                <el-option label="退款中" :value="1"></el-option>
                <el-option label="退款失败" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="审核状态">
              <el-select placeholder="请选择" v-model="form.auditStatus">
                <el-option label="全部" :value="null"></el-option>
                <el-option label="未完成" :value="1"></el-option>
                <el-option label="完成" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item>
              <el-button style="margin-left:60px" type="primary" @click="searchFn">查询</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-button
              style="margin-left:60px"
              type="primary"
              v-if="hasPermission('AdminAllowanceRefundProvider.refundListExport')"
              @click="exporfun"
            >导出</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 主页列表 -->
    <div class="listDiv" v-loading="tableLoading">
      <!-- table列表 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="applySn" label="单号">
          <template slot-scope="scope">
            <p>补贴单号:{{scope.row.applySn}}</p>
            <p>流水单号:{{scope.row.orderSn}}</p>
          </template>
        </el-table-column>
        <el-table-column prop="refundId" label="退款单号"></el-table-column>
        <el-table-column prop="payment" label="付款方式"></el-table-column>
        <el-table-column prop="userInfo" label="用户信息">
          <template slot-scope="scope">{{scope.row.userInfo | phonereg}}</template>
        </el-table-column>

        <el-table-column prop="region" label="省市"></el-table-column>
        <el-table-column prop="hospitalName" label="医院名称"></el-table-column>
        <el-table-column prop="projectName" label="项目"></el-table-column>
        <el-table-column prop="oldMoney" label="消费金额"></el-table-column>
        <el-table-column prop="refundMoney" label="退款金额"></el-table-column>
        <el-table-column prop="money" label="剩余金额"></el-table-column>
        <el-table-column prop="recommenderInfo" label="推荐人信息"></el-table-column>
        <el-table-column prop="team" label="团队"></el-table-column>
        <el-table-column prop="butlerInfo" label="管家信息">
          <template slot-scope="scope">{{scope.row.butlerInfo | phonereg}}</template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间"></el-table-column>
        <el-table-column prop="refundTime" label="退款时间"></el-table-column>
        <el-table-column prop="refundType" label="审核状态"></el-table-column>
        <el-table-column prop="intoStatus" label="入账状态"></el-table-column>
        <el-table-column prop="refundStatusName" label="退款状态">
          <!-- <template slot-scope="scope">
            <span v-if="scope.row.refundStatus==1">受理中</span>
            <span v-if="scope.row.refundStatus==2">失败</span>
            <span v-if="scope.row.refundStatus==0">成功</span>
          </template>-->
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200">
          <template slot-scope="scope">
            <div>
              <div v-if="hasPermission('AdminAllowanceRefundProvider.editStopStart')">
                <el-button
                  type="text"
                  size="small"
                  v-if="scope.row.status==1"
                  @click="stopDialogFn(scope.row.reason,scope.row.id)"
                >暂停</el-button>
              </div>
              <el-button
                v-if="hasPermission('AdminAllowanceRefundProvider.doReturnRefund')"
                type="text"
                @click="toRoutes('subsidyRefundRM',scope.row.id)"
                size="small"
              >回款</el-button>
              <!-- <el-button type="text" @click="toRoutes('subsidyRefundTD',scope.row.userId)" size="small">明细</el-button> -->
              <el-button
                v-if="hasPermission('AdminAllowanceProvider.detailProject')"
                type="text"
                @click="toRoutes('subsidyManageInfo',scope.row.id)"
                size="small"
              >详情</el-button>
              <!--    v-if="hasPermission('AdminAllowanceProvider.detailProject')"   v-if="scope.row.repaymentStatus>0"-->
              <el-button
                v-if="scope.row.repaymentStatus>0 &&(hasPermission('AdminAllowanceRefundProvider.refundRepayment') || hasPermission('AdminAllowanceRefundProvider.refundRepaymentInfo')) "
                type="text"
                size="small"
                @click="editfn(scope.row,1)"
              >{{scope.row.repaymentStatus==1?"全款项目打款":'打款信息'}}</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagesCon">
        <div>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="listForm.pageNum"
            :page-sizes="page_sizes"
            :page-size="listForm.limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page_totals"
          ></el-pagination>
        </div>
      </div>
      <!-- 暂停弹出窗 -->
      <el-dialog
        :title="params.repaymentStatus==1?'全款项目打款' :(params.repaymentStatus==2?'打款信息' :'暂停') "
        :visible.sync="stopDialog"
        width="480px"
      >
        <el-form :inline="true" ref="form" label-width="100px" :model="params" :rules="rules">
          <el-row v-if="!params.repaymentStatus">
            <el-col :span="24">
              <el-form-item label="上次操作原因">
                <span class="spanToInput">{{stopList.note | filterNull}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="操作人">
                <span class="spanToInput">{{stopList.name | filterNull}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="暂停理由">
                <el-input v-model="stopForm.note"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-else>
            <el-col :span="24">
              <p style="color:red;">*该全款项目订单原支付方式已超出线上原路退回时效，需人工打款退款
订单实付现金{{params.limit}}</p>
            </el-col>
            <el-col :span="24">
              <el-form-item label="用户银行" prop="cardId">
                <el-select
                  placeholder="请选择"
                  v-model="params.cardId"
                  :disabled="params.repaymentStatus==2"
                >
                  <el-option
                    :label="item.name+'/'+item.card"
                    :value="item.cardId"
                    v-for="(item, index) in usrbarnk"
                    :key="index"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="打款金额" prop="amount">
                <el-input v-model="params.amount" :disabled="params.repaymentStatus==2"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="打款日期" prop="time">
                <span v-if="params.repaymentStatus==2">{{params.time}}</span>
                <el-date-picker
                  v-else
                  v-model="params.time"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  type="datetime"
                  placeholder="选择日期时间"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="打款银行" prop="bankcard">
                <el-select
                  placeholder="请选择"
                  v-model="params.bankcard"
                  :disabled="params.repaymentStatus==2"
                >
                  <el-option label="6226661401701333" value="6226661401701333"></el-option>
                  <el-option label="6226621407581295" value="6226621407581295"></el-option>
                  <el-option label="127912425910301" value="127912425910301"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <span slot="footer" class="dialog-footer" v-if="params.repaymentStatus!=2">
          <el-button @click="stopDialog = false" v-if="params.repaymentStatus!=1">取 消</el-button>
          <el-button type="primary" @click="stopSubmitFn()">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { regionDropDown } from "@/api/area";
import {
  refundList,
  getUserBankCard,
  refundRepayment,
  refundRepaymentInfo
} from "@/api/subsidyRefund";
import { editStopStart, editStopStartNew } from "@/api/subsidyManage";
import { hospitalDropDown } from "@/api/doctorManage";
import { exportfile } from "@/api/commjs/exprot";
export default {
  name: "subsidyRefundIndex",
  data() {
    var validatePass = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入金额"));
      } else if (value > this.params.limit) {
        callback(new Error("请输入金额不能大于实付现金"));
      } else {
        callback();
      }
    };
    return {
      rules: {
        bankcard: [
          {
            required: true,
            message: "请输入打款银行",
            trigger: "blur"
          }
        ],
        time: [
          {
            required: true,
            message: "请输入打款日期",
            trigger: "blur"
          }
        ],
        amount: [{ validator: validatePass, trigger: "blur" }],
        cardId: [
          {
            required: true,
            message: "请输入用户银行",
            trigger: "blur"
          }
        ]
      },
      usrbarnk: [],
      options: [],
      stopDialog: false,
      hospitalOption: [],
      dates: "",
      tableLoading: true,
      createdAt: [],
      refundTime: [],
      stopList: {},
      form: {
        pageNum: 1,
        pageSize: 10,
        applySn: null,
        realname: null,
        username: null,
        hospitalId: null,
        createdAtStart: null,
        createdAtEnd: null,
        refundTimeStart: null,
        refundTimeEnd: null,
        refundStatus: null,
        province: null,
        city: null,
        auditStatus: null
      },
      tableData: [],
      page_sizes: [10, 30, 50, 100],
      page_totals: 60,
      listForm: {
        pageNum: 1,
        pageSize: 10
      },
      params: {},
      stopForm: {
        id: null,
        status: 0,
        note: ""
      }
    };
  },
  inject: ["reload"],
  filters: {
    cardType: function(e) {
      return window.helper.cardType(String(e));
    },
    filterNull(e) {
      if (!e) {
        return "暂无";
      } else {
        return e;
      }
    }
  },
  mounted() {
    this.getOption();
    this.getList(this.listForm);
    this.getArea();
  },
  methods: {
    async editfn(data) {
      // console.log(data);
      // data.repaymentStatus = 2
      this.params = {
        repaymentMsg: data.repaymentMsg,
        id: data.allwRefundId,
        userId: data.userId,
        repaymentStatus: data.repaymentStatus,
        limit: (data.refundMoney - data.refundUsedGoldCoin).toFixed(2)
      };
      if (data.repaymentStatus > 0) {
        let res = await getUserBankCard({ userId: data.userId });
        //  console.log(res);
        if (res.data.code == 0) {
          this.usrbarnk = res.data.data;
        }
      }
      if (data.repaymentStatus == 2) {
        let state = await refundRepaymentInfo({ id: data.allwRefundId });
        if (state.data.code == 0) {
          this.params = { ...state.data.data, ...this.params };
        }
      }
      this.stopDialog = true;
    },
    // 省市区
    getArea() {
      regionDropDown().then(res => {
        const newArr = [];
        res.data.data.forEach((item1, index) => {
          newArr.push({
            value: item1.id,
            label: item1.name
          });
          if (item1.children != null) {
            newArr[index]["children"] = [];
            item1.children.forEach(item2 => {
              newArr[index]["children"].push({
                value: item2.id,
                label: item2.name
              });
            });
          }
        });
        this.options = newArr;
      });
    },
    handleChange(value) {
      console.log(value);
      this.form.province = value[0];
      this.form.city = value[1];
    },
    exporfun() {
      exportfile(
        "com.mmk.reservation.api.AdminAllowanceRefundProvider/1.0.0/refundListExport.html",
        this.form
      );
    },
    //按钮权限
    hasPermission(e) {
      return window.helper.hasPermission(e);
    },
    //获取相应的列表
    getOption() {
      // 医院列表
      hospitalDropDown().then(res => {
        let resData = res.data.data;
        let newData = [];
        resData.forEach(e => {
          newData.push({
            value: e.id + "",
            label: e.name
          });
        });
        this.hospitalOption = newData;
      });
    },
    //成功状态弹窗
    succStatus(txt) {
      this.$message({
        message: txt + "成功",
        type: "success"
      });
    },
    //失败状态弹窗
    errorStatus(txt) {
      this.$message.error(txt + "失败");
    },
    //查询
    searchFn() {
      this.form.pageNum = 1;
      if (this.createdAt != null) {
        if (this.createdAt.length) {
          this.form.createdAtStart = this.createdAt[0];
          this.form.createdAtEnd = this.createdAt[1];
        }
      } else {
        this.form.createdAtStart = null;
        this.form.createdAtEnd = null;
      }
      if (this.refundTime != null) {
        if (this.refundTime.length) {
          this.form.refundTimeStart = this.refundTime[0];
          this.form.refundTimeEnd = this.refundTime[1];
        }
      } else {
        this.form.refundTimeStart = "";
        this.form.refundTimeEnd = "";
      }
      console.log(this.form);
      this.getList(this.form);
    },
    //列表数据获取
    getList(e) {
      this.tableLoading = true;
      let datas = e;
      refundList(datas)
        .then(res => {
          if (!res.data.code) {
            console.log(res);
            this.tableData = res.data.data.list;
            this.page_totals = res.data.data.count;
          } else {
            this.$message.error(res.data.msg);
          }
          this.tableLoading = false;
        })
        .catch(error => {
          this.$message.error(error);
        });
    },
    // 路由跳转
    toRoutes(e, userId) {
      let route = { name: e, query: { userId: userId } };
      // this.$router.push(route);
      let routeUrl = this.$router.resolve(route);
      window.open(routeUrl.href, "_blank");
    },
    //改变页面条数
    handleSizeChange(val) {
      this.form.pageSize = val;
      this.getList(this.form);
    },
    //选择页数
    handleCurrentChange(val) {
      this.form.pageNum = val;
      this.getList(this.form);
    },
    handleClose() {
      this.stopDialog = false;
    },
    //暂停
    stopDialogFn(e, id) {
      this.params = {};

      this.stopList = e;
      this.stopForm["id"] = Number(id);
      this.stopDialog = true;
    },
    //暂停提交
    stopSubmitFn() {
      if (JSON.stringify(this.params) == "{}") {
        //暂停
        let datas = this.stopForm;
        editStopStartNew(datas)
          .then(res => {
            this.stopDialog = false;
            if (!res.data.code) {
              this.succStatus("暂停");
              this.reload();
            } else {
              this.$message.error(res.data.msg);
            }
          })
          .catch(error => {
            this.stopDialog = false;
            this.$message.error(error);
          });
      } else {
        //打款
        this.$refs["form"].validate(async valid => {
          if (valid) {
            let res = await refundRepayment(this.params);
            // console.log(res);
            this.$message.warning(res.data.msg);
            if (res.data.code == 0) {
              this.stopDialog = false;
              this.getList(this.form);
            }
          }
        });
      }
    }
  }
};
</script>
<style scoped>
/* 分页 */
.pagesCon {
  height: 40px;
  margin-top: 20px;
}
.pagesCon > div {
  float: right;
}
/* 表单样式修改 */
.el-range-editor--medium.el-input__inner {
  width: 236px;
}
</style>
